<template>
	<view class="big_box">
		<u-navbar title="提现" :autoBack="true" :border="false"></u-navbar>
		<view class="container">
			<!-- 用户信息卡片 -->
			<view class="stats-card" :style="{backgroundImage: `url(${selectedImage})`}">
				<view class="card-content">
					<image class="avter" :src="user_info.avatar" mode=""></image>
					<view class="user-info">
						<view class="nickname">
							{{user_info.nickname || ''}}
						</view>
					</view>
					<view class="btn" @click="toWithdrawRecord">
						提现记录
					</view>
				</view>
			</view>

			<!-- 表单区域 -->
			<view class="form-container">
				<u--form labelPosition="left" :model="formData" :rules="rules" ref="formRef" labelWidth="120">
					<!-- 可提现金额 -->
					<u-form-item label="可提现金额(元)" prop="de_money">
						<u--input v-model="user_info.money" disabled disabledColor="#F6F6F6"
							placeholder="0.00"></u--input>
					</u-form-item>

					<!-- 姓名 -->
					<u-form-item label="姓名" prop="alipay_name" required>
						<u--input v-model="formData.alipay_name" placeholder="请输入真实姓名"></u--input>
					</u-form-item>

					<!-- 支付宝账户 -->
					<u-form-item label="支付宝账户" prop="alipay_account" required>
						<u--input v-model="formData.alipay_account" placeholder="请输入支付宝账号"></u--input>
					</u-form-item>

					<!-- 提现金额 -->
					<u-form-item label="提现金额(元)" prop="money" required>
						<u--input v-model="formData.money" @input="handleMoneyChange" placeholder="请输入提现金额"
							type="number"></u--input>

					</u-form-item>
				</u--form>

				<view class="amount-tips">
					<text>手续费: {{sxf_price}}元</text>
					<text>实际到账: {{true_money}}元</text>
				</view>
			</view>

			<!-- 提交按钮 -->
			<u-button class="submit-btn" type="primary" text="确定" @click="submit" :customStyle="{
					marginTop: '40rpx',
					height: '90rpx',
					fontSize: '32rpx'
				}"></u-button>

			<!-- 温馨提示 -->
			<view class="tips-container">
				<view class="tips-title">
					温馨提示:
				</view>
				<view class="tips-item">
					1、可提现时间为国家法定工作日，9:00-18:00
				</view>
				<view class="tips-item">
					2、每天只能提现一次
				</view>
				<view class="tips-item">
					3、提现后，第二天到账
				</view>
				<!-- <view class="tips-item">
					4、最低提现金额1元
				</view> -->
				<view class="tips-item">
					4、提现手续费{{sxf_bfb}}%
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from "vuex";
	import api from '@/api/index.js'
	export default {
		data() {
			return {
				selectedImage: '/static/index_image/tx_banner.png',
				formData: {
					alipay_name: '', // 姓名
					alipay_account: '', // 支付宝账户
					money: '' // 提现金额
				},
				rules: {
					alipay_name: {
						type: 'string',
						required: true,
						message: '请输入姓名',
						trigger: ['blur', 'change']
					},
					alipay_account: [{
							required: true,
							message: '请输入支付宝账号',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								// 简单的支付宝账号验证
								return /^1[3-9]\d{9}$/.test(value) ||
									/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
							},
							message: '请输入正确的支付宝账号(手机或邮箱)',
							trigger: ['blur', 'change']
						}
					],

					money: [{
							required: true,
							message: '请输入提现金额',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								if (!value) return false;

								const inputMoney = parseFloat(value);
								const availableMoney = parseFloat(this.userInfo.money || 0);

								if (isNaN(inputMoney)) {
									return false;
								}

								// if (inputMoney < 1) {
								// 	return false;
								// }

								if (inputMoney > availableMoney) {
									return false;
								}

								return true;
							},
							message: '金额不能大于可提现金额',
							trigger: ['blur', 'change']
						}

					]
				},
				sxf_bfb: 0, // 手续费百分比
				sxf_price: '0.00', // 手续费金额
				true_money: '0.00', // 实际到账金额
				user_info: {},
				getFeeRate: null,
			}
		},

		onLoad() {
			// 如果用户已登录，填充用户信息
			// if (uni.getStorageSync('token')) {
			// 	this.userInfo = uni.getStorageSync('userInfo') || {};
			// }
			this.getUserinfo()

		},
		created() {
			this.initDebounce();
		},
		methods: {
			getUserinfo() {
				api.getUserinfo().then(res => {
					if (res.response.statusCode == 200) {
						this.user_info = res.data.data
						if (res.data.data.alipay_name) {
							this.formData.alipay_name = res.data.data.alipay_name
						}
						if (res.data.data.alipay_account) {
							this.formData.alipay_account = res.data.data.alipay_account
						}


					}
				}).catch(err => {
					console.error(err)
				})
			},

			calculateFee(value) {
				api.getJisuan({
					money: value
				}).then(res => {
					this.sxf_price = res.data.data.sxf;
					this.true_money = res.data.data.true_money;
					this.sxf_bfb = res.data.data.bfb;
				});
			},
			// 金额变化处理
			handleMoneyChange(value) {
				if (!value) {
					this.resetFeeData();
					return;
				}
				if (isNaN(value)) {
					this.formData.money = '';
					return;
				}
				if (value.indexOf('.') !== -1 && value.split('.')[1].length > 2) {
					this.formData.money = parseFloat(value).toFixed(2);
					return;
				}
				const amount = parseFloat(value);
				const availableAmount = parseFloat(this.user_info.money || 0);
				if (amount > availableAmount) {
					this.formData.money = availableAmount.toFixed(2);
					this.$nextTick(() => {
						this.debouncedFeeCalculator(this.formData.money);
					});
					return;
				}
				this.debouncedFeeCalculator(value); // 防抖调用
			},
			// 初始化防抖
			initDebounce() {
				this.debouncedFeeCalculator = this.debounce((value) => {
					this.calculateFee(value);
				}, 500);
			},


			// 重置手续费数据
			resetFeeData() {
				this.sxf_price = '0.00';
				this.true_money = '0.00';
				this.sxf_bfb = '0';
			},
			// 防抖函数实现
			debounce(func, wait) {
				let timeout;
				return function(...args) {
					const context = this;
					clearTimeout(timeout);
					timeout = setTimeout(() => {
						func.apply(context, args);
					}, wait);
				};
			},




			// 提交表单
			async submit() {
				try {
					const valid = await this.$refs.formRef.validate();
					if (!valid) return;

					uni.showLoading({
						title: '处理中...'
					});

					// 再次验证金额是否合法
					const inputMoney = parseFloat(this.formData.money);
					const availableMoney = parseFloat(this.user_info.money || 0);

					if (inputMoney > availableMoney) {
						uni.showToast({
							title: '提现金额不能超过可提现金额',
							icon: 'none'
						});
						return;
					}

					// 调用提现接口
					const res = await api.getwithdraw({
						alipay_name: this.formData.alipay_name,
						alipay_account: this.formData.alipay_account,
						money: this.formData.money,
					});

					uni.hideLoading();

					if (res.response.statusCode == 200) {
						uni.showToast({
							title: '提现申请提交成功',
							icon: 'success'
						});

						// 更新用户可提现金额
						this.user_info.money = (availableMoney - inputMoney).toFixed(2);
						// uni.setStorageSync('userInfo', this.user_info);

						// 清空表单
						this.formData.money = '';
						this.sxf_price = '0.00';
						this.true_money = '0.00';
						uni.navigateTo({
							url:'/pages/mine/withdrawRecord'
						})
							
						if(res.data.code==0){
							uni.showToast({
								title: res.data.msg,
								icon: 'none'
							});
						}
					} else {
						uni.showToast({
							title: res.data.msg || '提现失败',
							icon: 'none'
						});
					}
				} catch (err) {
					uni.hideLoading();
					if (err.errMsg && err.errMsg.includes("validate")) {
						uni.showToast({
							title: '请完善表单信息',
							icon: 'none'
						});
					} else {
						// console.error(err);
						uni.showToast({
							title: err,
							icon: 'none'
						});
					}
				}
			},


			// 跳转到提现记录页面
			toWithdrawRecord() {
				uni.navigateTo({
					url: '/pages/mine/withdrawRecord'
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@mixin flex-center-between {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	@mixin flex-center-column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.big_box {
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	.container {
		padding: 20rpx 30rpx;
		margin-top: 3rem;

	}

	// 顶部banner
	.stats-card {
		height: 240rpx;
		border-radius: 20rpx;
		margin-bottom: 30rpx;
		background-repeat: no-repeat;
		background-size: 100% 100%;
		overflow: hidden;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.1);

		.card-content {
			padding: 40rpx 30rpx;
			@include flex-center-between;

			.avter {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				border: 4rpx solid rgba(255, 255, 255, 0.5);
			}

			.user-info {
				flex: 1;
				margin-left: 20rpx;
				color: #fff;

				.nickname {
					font-size: 36rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}

				.phone {
					font-size: 28rpx;
					opacity: 0.9;
				}
			}

			.btn {
				background: rgba(255, 255, 255, 0.2);
				color: #fff;
				padding: 12rpx 24rpx;
				border-radius: 30rpx;
				font-size: 24rpx;
			}
		}
	}

	// 表单容器
	.form-container {
		background: #fff;
		border-radius: 20rpx;
		padding: 20rpx 30rpx;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);

		// margin-top: ;
		.yuan {
			color: #999;
			font-size: 28rpx;
			margin-left: 10rpx;
		}

		.amount-tips {
			@include flex-center-between;
			padding: 20rpx 0;
			font-size: 24rpx;
			color: #666;
			border-top: 1rpx solid #f5f5f5;
			margin-top: 20rpx;
		}
	}

	// 提交按钮
	.submit-btn {
		border-radius: 50rpx;
		background: linear-gradient(45deg, #7dc5eb, #00aaff);
		border-color: #7dc5eb;
	}

	// 温馨提示
	.tips-container {
		margin-top: 50rpx;
		padding: 30rpx;
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 10rpx 20rpx rgba(0, 0, 0, 0.05);

		.tips-title {
			font-size: 30rpx;
			font-weight: bold;
			margin-bottom: 20rpx;
			color: #333;
		}

		.tips-item {
			font-size: 14px;
			color: #AFAFAF;
			line-height: 1.8;
			padding-left: 20rpx;
			position: relative;

			// &::before {
			// 	content: "";
			// 	position: absolute;
			// 	left: 0;
			// 	top: 18rpx;
			// 	width: 8rpx;
			// 	height: 8rpx;
			// 	background: #2979ff;
			// 	border-radius: 50%;
			// }
		}
	}
</style>